// let router = require('express').Router();
const path = require("path");
const fs = require("fs");
const {hashLink, escapeUrl} = require("./util");
const d = {}
d.htmlHandler = (req, res, next) => {
    const map = req.app.locals.map;
    const contentTypeMap = req.app.locals.contentTypeMap;

    let hashWithExt = req.path.startsWith("/") ? req.path.substring(1, req.path.length) : req.path;
    hashWithExt = decodeURIComponent(hashWithExt);
    const path = map.get(hashWithExt).pathname;
    let ext = path.substring(path.lastIndexOf('.') + 1);
    if (!ext in contentTypeMap)
        ext = "default";
    const desc = map.get(hashWithExt).htmlDesc;
    if (!contentTypeMap.hasOwnProperty(ext)) {
        ext = "default";
    }
    res.writeHead(200, {
        'Content-Type': contentTypeMap[ext]
    });
    console.log(`sending ${path}`);
    let readStream = fs.createReadStream(path);
    readStream.pipe(res)
}
d.folderHandler = (req, res, next) => {
    const map = req.app.locals.map;
    const contentTypeMap = req.app.locals.contentTypeMap;

    const hashWithExt = req.path.startsWith("/") ? req.path.substring(1, req.path.length) : req.path;
    const hash = hashWithExt.substring(0, hashWithExt.lastIndexOf("."));
    const pathname = map.get(hashWithExt).pathname;
    let ext = pathname.substring(pathname.lastIndexOf('.') + 1);
    if (!ext in contentTypeMap)
        ext = "default";
    const desc = map.get(hashWithExt).htmlDesc;
    // res.writeHead(200, {
    //     'Content-Type': contentTypeMap[ext]
    // });
    res.contentType(contentTypeMap[ext]);
    console.log(`sending ${path}`);
    const dir = pathname;
    const filenames = [];
    fs.readdirSync(dir).forEach((file)=>{
        const pathname=path.join(dir,file)
        if(fs.statSync(pathname).isFile()) {
            filenames.push(path.basename(pathname));
        }
    })
    let content = "";
    filenames.forEach(fn => {
        const key = map.get(`${hash}_${escapeUrl(fn)}`);
        // const item = `<li><a href="/${encodeURIComponent(key.hashWithExt).replaceAll("(", "%28").replaceAll(")", "%29")}">${fn}</a></li>`;
        const item = `<li><a href="/${encodeURIComponent(key.hashWithExt)}">${fn}</a></li>`;
        content += item;
    });
    res.send(`
<html>
    <ul>
    ${content}
    </ul>
</html>
    `);
}
d.mediaFileHandler = (req, res, next) => {
    const map = req.app.locals.map;
    const contentTypeMap = req.app.locals.contentTypeMap;
    // const hashWithExt = req.path.startsWith("/") ? req.path.substring(1, req.path.length) : req.path;
    let hashWithExt = req.path.startsWith("/") ? req.path.substring(1, req.path.length) : req.path;
    hashWithExt = decodeURIComponent(hashWithExt);
    const path = map.get(hashWithExt).pathname;

    if (req.query["sendpath"] && req.query["sendpath"] === "1") {
        res.contentType(contentTypeMap["mp4"]);
        res.send(path);
    } else {
        res.sendFile(path);
    }
}
d.mediaHtml5PlayerHandler = (req, res, next) => {
    const map = req.app.locals.map;
    let hashWithExt = req.path.startsWith("/") ? req.path.substring(1, req.path.length) : req.path;
    hashWithExt = decodeURIComponent(hashWithExt);
    const path = map.get(hashWithExt).pathname;
    // res.sendFile(__dirname + '/index.html'); // TODO, 将请求的视频路径写到index.html中
    res.send(`
<!DOCTYPE html>
<html lang="en">
<head>
  <title>Video Player</title>
</head>
<body>
<video src="${path}" width="1080px"
       controls></video>
</body>
</html>
    `)
}
d.mediaHtml5DataHandler = (req, res, next) => {
    const map = req.app.locals.map;

    const range = req.headers.range
    // const videoPath = 'E:/test.mp4';
    const videoRequestPath = req.path.startsWith("/") ? req.path.substring(1, req.path.length) : req.path;
    let hashWithPrefix = videoRequestPath.startsWith("videoplayer") ? videoRequestPath.substring("videoplayer".length, videoRequestPath.length): videoRequestPath;
    const hashWithExt = hashWithPrefix.startsWith("/") ? hashWithPrefix.substring(1, hashWithPrefix.length) : hashWithPrefix;
    const videoPath = map.get(hashWithExt).pathname;

    const videoSize = fs.statSync(videoPath).size;
    const chunkSize = 1 * 1e6;
    const start = Number(range.replace(/\D/g, ""))
    const end = Math.min(start + chunkSize, videoSize - 1)
    const contentLength = end - start + 1;
    const headers = {
        "Content-Range": `bytes ${start}-${end}/${videoSize}`,
        "Accept-Ranges": "bytes",
        "Content-Length": contentLength,
        "Content-Type": "video/mp4"
    }
    res.writeHead(206, headers)
    const stream = fs.createReadStream(videoPath, {
        start,
        end
    })
    stream.pipe(res)
}

module.exports = d;
